//准备代替 functions.dart

import 'dart:math';

enum Method { //  计算方法
  // 加减乘除
  add,
  sub,
  mul,
  div,
  power
  //后面准备添加sin cos tan等
}

class MathVariable {
  String name;
  bool showout = false;// 默认不显示计算步骤
  List<Map<Method,dynamic>> equation = []; //  计算步骤事务列表
  MathVariable(this.name); // 构造函数设置变量名

  add (dynamic value) {
    equation.add({Method.add: value});
    return this;
  }

  sub (dynamic value) {
    equation.add({Method.sub: value});
    return this;
  }

  mul (dynamic value) {
    equation.add({Method.mul: value});
    return this;
  }

  div (dynamic value) {
    equation.add({Method.div: value});
    return this;
  }

  power (dynamic value) {
    equation.add({Method.power: value});
    return this;
  }

  getValue (dynamic value) { //引入自变量运算
    String shower = "无视符号优先级，从左到右运算  "+ name + "=$value   " ;
    if (value is int) {
      value = value+0.0;
    }
    double result = value;
    shower+= "$name";
    for (Map<Method,dynamic> map in equation) {
      if (map[Method.add] != null) {
        if (map[Method.add] is int ||  map[Method.add] is double) {
          result += map[Method.add];
          shower+= " + ${map[Method.add]+0.0}";
        } else if (map[Method.add] is MathVariable) {
          result += value;
          shower+= " + $name";
        }
      }
      if (map[Method.sub] != null) {
        if (map[Method.sub] is int ||  map[Method.sub] is double) {
          result -= map[Method.sub];
          shower+= " - ${map[Method.sub]+0.0}";
        } else if (map[Method.sub] is MathVariable) {
          result -= value;
          shower+= " - $name";
        }
      }
      if (map[Method.mul] != null) {
        if (map[Method.mul] is int ||  map[Method.mul] is double) {
          result *= map[Method.mul];
          shower+= " * ${map[Method.mul]+0.0}";
        } else if (map[Method.mul] is MathVariable) {
          result *= value;
          shower+= " * $name";
        }
      }
      if (map[Method.div] != null) {
        if (map[Method.div] is int ||  map[Method.div] is double) {
          result /= map[Method.div];
          shower+= " / ${map[Method.div]+0.0}";
        } else if (map[Method.div] is MathVariable) {
          result /= value;
          shower+= " / $name";
        }
      }
      if (map[Method.power] != null) {
        if (map[Method.power] is int ||  map[Method.power] is double) {
          result = pow(result, map[Method.power]) as double;
          shower+= " ^ ${map[Method.power]+0.0}";
        }
      }
    }
    if (showout) {
      print(shower); // 显示计算步骤
    }
    return result;
  }

  void reset () {
    equation.clear();
  }



}

void main () {
  MathVariable x = MathVariable("x")..showout=true; // true 则 显示计算步骤

  print(x.mul(3).add(2).div(x).getValue(2)); // x是2的情况
  x.reset(); //重置运算，让下一步对x的计算不会累积在之前的result上

  print(x.mul(3).add(2).div(x).getValue(3)); // x是3的情况
  x.reset(); //重置运算

  print(x.mul(3).add(2).div(x).getValue(4)); // x是4的情况
  x.reset();
}